/* eslint-disable no-trailing-spaces */
var nodemailer = require('nodemailer');
var bodyParser = require('body-parser');

var ipMarkMap = {};

function getRemoteIp (req) {
  if (req.headers['x-forwarded-for']) {
    return req.headers['x-forwarded-for'].split(',').pop();
  }
  return req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
}

exports = module.exports = function (app) {
  app.use(bodyParser.json()); // support json encoded bodies
  app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

  var transporter = nodemailer.createTransport('smtps://admin@diw-612.com:Qq5863303@smtp.exmail.qq.com');

  app.post('/sendEmail', function (req, res) {
    var body = req.body;
    var text = '';
    text += '<p>お名前：' + (body.contactName || '--') + '</p>';
    text += '<p>社名：' + (body.contactCompany || '--') + '</p>';
    text += '<p>メールアドレス：' + (body.contactEmail || '--') + '</p><hr/>';
    text += '<p>お問い合わせ内容：<br/>' + (body.contactMsg || '--') + '</p>';
    var subject = '';
    subject += (body.contactName || '--') + ' from ' + (body.contactCompany || '--');
    if (!body.contactName.trim() || !body.contactCompany.trim() || !body.contactEmail.trim() || body.contactMsg.trim().length < 10) {
      res.send({ success: false });
      return;
    }
    var ip = getRemoteIp(req);
    if (ip) {
      if (ipMarkMap[ip] && new Date() - ipMarkMap[ip] < 6 * 60 * 60 * 1000) { // 单个IP，6个小时之内只允许发送一次
        res.send({ success: true });
        return;
      } else {
        ipMarkMap[ip] = new Date();
      }
    }

    // console.info(subject, text);
    var mailOptions = {
      from: '"DIW" <admin@diw-612.com>', // sender address
      to: 'info@diw-612.com', // list of receivers
      // to: '496115864@qq.com', // list of receivers
      subject: subject, // Subject line
      // text: 'Hello world ?', // plaintext body
      html: text, // html body
    };

// send mail with defined transport object
    transporter.sendMail(mailOptions, function (error, info) {
      if (error) {
        res.send({ success: false });
        return console.log(error);
      }
      console.log('Message sent: ' + info.response);
      res.send({ success: true });
    });

  });
};


